//
//  YLCRC16Tool.m
//  Yilong
//
//  Created by DisCover on 2021/6/22.
//

#import "YLCRC16Tool.h"

@implementation YLCRC16Tool
//将16进制的字符串转换成NSData

+ (NSMutableData *)convertHexStrToData:(NSString *)str {
	if (!str || [str length] == 0) {
		return nil;
	}


	NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];

	NSRange range;

	if ([str length] %2 == 0) {
		range = NSMakeRange(0,2);

	} else {
		range = NSMakeRange(0,1);

	}

	for (NSInteger i = range.location; i < [str length]; i += 2) {
		unsigned int anInt;

		NSString *hexCharStr = [str substringWithRange:range];

		NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];


		[scanner scanHexInt:&anInt];

		NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];

		[hexData appendData:entity];


		range.location += range.length;

		range.length = 2;

	}
	return hexData;

}
+ (NSString *)convertDataToHexStr:(NSData *)data {
	if (!data || [data length] == 0) {
		return @"";

	}

	NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];



	[data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange,BOOL *stop) {
	         unsigned char *dataBytes = (unsigned char*)bytes;

	         for (NSInteger i =0; i < byteRange.length; i++) {
			 NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) &0xff];

			 if ([hexStr length] == 2) {
				 [string appendString:hexStr];

			 } else {
				 [string appendFormat:@"0%@", hexStr];

			 }

		 }

	 }];


	return string;

}

+ (NSString *)getCrc16_MODBUSWithString:(NSString *)str {

	NSArray *array = [[NSArray alloc]initWithArray:[self seperateStr:str byLength:2]];
	unsigned short tmp = 0xffff;
	unsigned short ret1 = 0;
	Byte buff[10240] = {};

	for (int i = 0; i < array.count; i++) {
		buff[i] = [[self decimalStringFromHexString:array[i]] intValue];//  这个是10进制转换成16进制
	}

	for(int n = 0; n < array.count; n++) {
		tmp = buff[n] ^ tmp;
		for(int i = 0; i < 8; i++) { /*此处的8 -- 指每一个char类型又8bit，每bit都要处理*/
			if(tmp & 0x01) {
				tmp = tmp >> 1;
				tmp = tmp ^ 0xa001;
			}
			else{
				tmp = tmp >> 1;
			}
		}
	}
	/*CRC校验后的值*/
	printf("校验后的值%X\n",tmp);
	/*将CRC校验的高低位对换位置*/
	ret1 = tmp >> 8;
	ret1 = ret1 | (tmp << 8);
	printf("高低位对换后的值ret: %X\n",ret1);

	NSString *returnStr = [NSString stringWithFormat:@"%X",ret1];
	return returnStr;
}
+ (NSMutableArray *)seperateStr:(NSString *)str byLength:(int)length {
//举例   828384  以 2个 为单位 拆分

	NSMutableArray *returnArray = [[NSMutableArray alloc] init];

	for (int i = 0; i < (str.length - length) + 1; i=i+length) {
		NSString *twoStr = [str substringWithRange:NSMakeRange(i, length)];
		[returnArray addObject:twoStr];
	}
	return returnArray;
}
+ (NSString *)decimalStringFromHexString:(NSString *)string {

	NSString * decimalStr = [NSString stringWithFormat:@"%lu",strtoul([string UTF8String],0,16)];
	return decimalStr;
}
@end
